import VueRouter from 'vue-router'

// 处理模块互相引用导致的问题
class AsyncRouter {
  get router() {
    return this._router || null
  }

  set router(router) {
    if (router instanceof VueRouter) {
      this._router = router
      this.registerRouteEvent()
    } else {
      this._router = null
      throw new Error('AsyncRouter set router not instance of VueRouter')
    }
  }

  get routeEvents () {
    if (!this._routeEvents) this._routeEvents = []
    return this._routeEvents
  }

  registerRouteEvent(name, callback) {
    const { router, routeEvents } = this

    // router 存在时候注册 routeEvents 中的事件
    if (router && routeEvents.length) {
      routeEvents.forEach(({ name, callback }) => router[name].call(router, callback))
      routeEvents.splice(0, routeEvents.length)
      routeEvents.length = 0
    }

    if (!name) return
    if (!['beforeEach', 'beforeResolve', 'afterEach'].includes(name)) {
      console.warn('registerRouteEvent warning: name is illegal')
      return
    }
    if (typeof callback !== 'function') {
      console.warn('registerRouteEvent warning: callback not function')
      return
    }

    if (router) router[name].call(router, callback)
    else routeEvents.push({ name, callback })
  }
}

export default new AsyncRouter()
